package net.kqinfo.core.controller.management;

import java.util.ArrayList;
import java.util.List;

import net.kqinfo.core.controller.management.condition.ModuleCondition;
import net.kqinfo.core.model.Module;

import com.jfinal.aop.Before;
import com.jfinal.core.Controller;
import com.jfinal.ext.render.DwzRender;
import com.jfinal.plugin.activerecord.Page;

public class ModuleController extends Controller{

	private static final String CREATE = "/WEB-INF/views/management/security/module/create.html";
	private static final String UPDATE = "/WEB-INF/views/management/security/module/update.html";
	private static final String LIST = "/WEB-INF/views/management/security/module/list.html";
	private static final String TREE = "/WEB-INF/views/management/security/module/tree.html";
	private static final String VIEW = "/WEB-INF/views/management/security/module/view.html";
	
	public ModuleCondition cond;
	
	public void tree(){
		Module module = Module.dao.findById(1);
		setAttr("module", module);
		render(TREE);
	}
	
	@Before(ModuleCondition.class)
	public void list(){
		StringBuilder sql = new StringBuilder();
		List<Object> paras = new ArrayList<Object>();
		cond.buildSql(sql, paras);
		Page<Module> page = Module.dao.paginate(cond.getPageNumber(), cond.getPageSize(), "select * ", sql.toString(), paras.toArray());
		setAttr("page", page);
		render(LIST);
	}
	
	@Before(ModuleCondition.class)
	public void create(){
		render(CREATE);
	}
	
	public void doCreate(){
		Module module = getModel(Module.class);
		
		Module parentModule = Module.dao.findById(module.get("parent_id"));
		if (parentModule == null) {
			DwzRender.error("模块添加失败：id=" + module.get("parent_id") + "的父模块不存在！");
		}
		
		try {
			module.save();
		} catch (Exception e) {
			DwzRender.error("模块添加失败：" + e.getMessage());
		}
		render(DwzRender.closeCurrentAndRefresh("page"));
	}
	
	public void view(){
		long id = getParaToLong(0, -1l);
		if (id == -1l) {
			render(DwzRender.error("请选择要查看的模块。"));
		}else{
			Module module = Module.dao.findById(id);
			setAttr("module", module);
		}
		render(VIEW);
	}
	
	public void update(){
		long id = getParaToLong(0, -1l);
		if (id == -1l) {
			render(DwzRender.error("请选择要修改的模块。"));
		}else{
			Module module = Module.dao.findById(id);
			setAttr("module", module);
		}
		render(UPDATE);
	}
	
	public void doUpdate(){
		Module module = getModel(Module.class);
		module.update();
		render(DwzRender.closeCurrentAndRefresh("page"));
	}
	
	public void delete(){
		long id = getParaToLong(0, -1l);
		if (id == -1l) {
			render(DwzRender.error("请选择要删除的模块。"));
		}else{
			Module.dao.deleteById(id);
		}
		render(DwzRender.success());
	}

	public ModuleCondition getCond() {
		return cond;
	}

	public void setCond(ModuleCondition cond) {
		this.cond = cond;
	}
	
}
